
/* header 登录转换 */
let uidn = localStorage.getItem('uid');
if (uidn != null) {
    let username = localStorage.getItem('username');
    $('#login').html(username).click(function(){
        var userRes = confirm('是否要退出登录');
        if(userRes == true){
            localStorage.removeItem('uid');
            localStorage.removeItem('username');
            location.href = './infor.html';
        }
    })
}else{
    $('#login').html('登录').click(function(){
        location.href = './login.html'
    })
}

/* nav下拉跳转 */
$("#nav div ul").on('click', 'li', function () {
    localStorage.setItem('pclass', $(this).attr('pclass'));
    localStorage.setItem('pid', $(this).attr('pid'));
    location.href = './infor.html';
})

let pclass = localStorage.getItem('pclass');
let pid = localStorage.getItem('pid');
url = `http://localhost:3000/${pclass}/${pid}`;
ajax(url)
function ajax(url) {
    axios.get(url)
        .then(function (res) {
            html += `<li pid="${res.data.id}" pclass="${res.data.pclass}">
                    <div id="tu">
                        <div id="box">
                            <div id="small">
                                <img id="img1" src="${res.data.img[0]}" alt="">
                                <div id="sharder"></div>
                            </div>
                            <div id="big">
                                <img id="img2" src="" alt="">
                            </div>
                        </div>
                        <ul>
                            <li><img src="${res.data.img[0]}" alt=""></li>
                            <li><img src="${res.data.img[1]}" alt=""></li>
                            <li><img src="${res.data.img[2]}" alt=""></li>
                            <li><img src="${res.data.img[3]}" alt=""></li>
                            <li><img src="${res.data.img[4]}" alt=""></li>
                        </ul>
                    </div>
                    <div id="inf">
                    <h2>${res.data.title}</h2>
                    <p>${res.data.intro}</p>
                    <span>${res.data.price}</span>
                    <br>
                    <button class="sub" pid="${res.data.id}" pclass="${res.data.pclass}">-</button><b>1</b><button class="add" pid="${res.data.id}" pclass="${res.data.pclass}">+</button>
                    <button class="addCart" pid="${res.data.id}" pclass="${res.data.pclass}">加入购物车</button>
                    </div>
                </li>`
            $('#main ul').html(html)
            new bbox({el:"#box"})
        })
        .catch(function (err) {
            console.log(err)
        })
}


/* 图片选项卡 */
$('#main ul').on('mouseenter', '#tu ul li', function () {
    let src = $(this).children().attr('src');
    console.log(src)
    $('#main ul').find('#tu #box #small #img1').attr('src', src)
})

/* 图片放大镜 */
class  bbox{
    constructor(obj){
        //定义变量
        this.el = document.querySelector(obj.el)
        this.small = this.el.querySelector('#small')
        this.lg = document.querySelector('#box')
        this.img1 = this.el.querySelector('#img1');
        this.img2 = this.el.querySelector('#img2');
        this.sharder  =this.el.querySelector('#sharder')
        this.big = this.el.querySelector('#big')
       
        this.bigImg  = this.el.querySelector('#img2')
       //鼠标移入移出,让遮罩和大图显示和隐藏
       this.small.onmouseenter = ()=>{
           this.sharder.style.display = 'block'
           this.big .style.display = 'block'

           var src = this.img1.getAttribute('src');
           console.log(src);
             this.img2.setAttribute('src',src);


            //调整遮罩和图片的比例关系
       //小图的宽/小遮罩宽 = 大图宽/大遮罩宽
       //大图宽 = 大遮罩宽*小图的宽/小遮罩宽
      /*  console.log(this.big.offsetWidth)
       console.log(this.small.offsetWidth)
       console.log(this.sharder.offsetWidth) */
      let bigImgWidth = this.big.offsetWidth*this.small.offsetWidth/this.sharder.offsetWidth
      let bigImgHeight = this.big.offsetHeight*this.small.offsetHeight/this.sharder.offsetHeight
     //offset只有在元素出现的时候才有值，元素隐藏掉了，所以不会有值
     //   console.log(bigImgWidth)
       this.bigImg.style.width = bigImgWidth+'px'

      //监听鼠标在小图上面的移动
      this.small.onmousemove = (e)=>{
        //   console.log(e)

           let sharderX = e.pageX - this.lg.offsetLeft - this.sharder.offsetWidth/2;

           let sharderY = e.pageY -this.lg.offsetTop-this.sharder.offsetHeight/2;
    // console.log(sharderX);
     //定边界
           if(sharderX<= 0){
              sharderX = 0;
          }
          if(sharderX>= this.small.offsetWidth-this.sharder.offsetWidth){ 
              sharderX= this.small.offsetWidth-this.sharder.offsetWidth;
         }
         


          if(sharderY<= 0){
              sharderY = 0;
          }
           
         if(sharderY>=this.small.offsetHeight-this.sharder.offsetHeight){
            sharderY = this.small.offsetHeight-this.sharder.offsetHeight;
         }

           this.sharder.style.left = sharderX +'px';
           this.sharder.style.top = sharderY+'px';
         
          
         let bigImgX = sharderX * bigImgWidth/this.small.offsetWidth
         
         let bigImgY = sharderY * bigImgHeight/this.small.offsetHeight
         
         this.bigImg.style.left = -bigImgX+'px';
         this.bigImg.style.top = -bigImgY+'px';
            
      }

       }
       this.small.onmouseleave = ()=>{
         this.sharder.style.display = 'none'
           this.big .style.display = 'none'
       }

   }
  }
 




    /* 数量加减 */
    $("#main ul").on("click", ".sub", function () {
        let pnum = parseInt($(this).next().html());
        if (pnum <= 1) {
            pnum = 1;
            alert('加入购物车数量最少为1');
        } else {
            pnum--;
            $(this).next().html(pnum);
        }
    })
    $("#main ul").on("click", ".add", function () {
        let pnum = parseInt($(this).prev().html());
        pnum++;
        $(this).prev().html(pnum);
    })

    var flag = true;
    var id = null;
    $("#main ul").on("click", ".addCart", function () {
        let uid = localStorage.getItem("uid");
        let pnum = parseInt($(this).prev().prev().html());
        if (uid == null) {
            alert('请先登录再加入购物车!')
        } else {
            if (pnum == 0) {
                alert('请先选择数量!')
            } else {

                cartsAPI = `http://localhost:3000/carts?uid=${uid}`;
                axios.get(cartsAPI)/* 找到属于某个用户的购物车 */
                    .then(function (res) {
                        res.data.forEach(function (v) {
                            if (v.pclass == pclass && v.pid == pid) {/* 如果pclass与pid同时相同，默认是购物车中已存在该商品，flag改为false，只需要修改数量 */
                                flag = false;
                                pnum = pnum + v.pnum;
                                id = v.id;
                            }
                        })
                        console.log(flag)
                        console.log(pid)
                        console.log(pclass)
                        if (flag == true) {
                            axios.post("http://localhost:3000/carts", { uid, pid, pnum, pclass })
                                .then(function (res) {
                                    alert('购物车添加成功!')
                                })
                        } else {
                            let altelAPI = `http://localhost:3000/carts/${id}`;
                            axios({
                                method: "patch",
                                url: altelAPI,
                                data: {
                                    pnum
                                }
                            }).then((res) => {
                                console.log(res.data)
                                alert('购物车添加成功!')
                                // id = null
                            })
                        }
                    })


            }
        }
    })